var appPath = getAppPath();	

$(function(){
	// 检索日期范围
	$("#queryDateStart").datebox({
		formatter:dtFmt,
		parser:dtParser
	});
	$("#queryDateEnd").datebox({
		formatter:dtFmt,
		parser:dtParser
	});
	
	var data = [{'id':'0','name':'[不限]'},{'id':'10','name':'未开始'},
	            {'id':'20','name':'进行中'},{'id':'30','name':'已结束'}];
	$("#queryNotifyState").combobox({
		data : data,
		valueField : 'id',
		textField : 'name',
		onLoadSuccess :function(){
			$("#queryNotifyState").combobox('select',0).combobox('enable');
		}
	});

	initJspGrid();
});

function doSearch() {
    $("#rightGrid").datagrid("load", {
    "sTitle" : $("#sTitle").val()
    });
}

function dtFmt(dt){
	var y = dt.getFullYear();
    var m = dt.getMonth()+1;
    var d = dt.getDate();
    return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);//格式化mm-dd
}
function dtParser(s){
    if (!s) return new Date();
    var ss = (s.split('-'));
    var y = parseInt(ss[0],10);
    var m = parseInt(ss[1],10);
    var d = parseInt(ss[2],10);
    if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
        return new Date(y,m-1,d);
    } else {
        return new Date();
    }
}

// 列表初始化
function initJspGrid(){
	
	$('#tmplGrid').datagrid({
	    url:appPath + "/itbNotify/getNotifyInfoPg.action",
	    height:'full',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    nowrap: false,// 换行
	    queryParams: getQueryParam(),
	    singleSelect:false,
	    // If set to true, clicking a checkbox will always select the row. 
	    // If false, selecting a row will not check the checkbox.
	    selectOnCheck:true,
	    // If true, the checkbox is checked/unchecked when the user clicks on a row. 
	    // If false, the checkbox is only checked/unchecked when the user clicks exactly on the checkbox.
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
			//微缩图
		    {field:'image',title:'缩略图',width:75,align:'center',sortable:false,
	        	formatter:function(image, rowData, rowIndex){
	        		var retUrl = '';
	        		if (rowData.image) {
	        			retUrl = '<a href="' + rowData.image + '" target="_blank">'
	        				+ '<div style="display:table;text-align:center;height:80px;width:100%">'
	        				+ '<span style="display:table-cell;vertical-align:middle">'
	        				//+ '<img src="' + rowData.image.replace('oss-cn-hangzhou.aliyuncs.com','img-cn-hangzhou.aliyuncs.com') + '@110h_128w_1l.png'
	        				+'<img src="' + rowData.image+'?x-oss-process=image/resize,m_pad,h_80,w_100,color_ffffff'
	        				+ '" style="display:inline;max-height:80px;max-width:100px"></span></div></a>';
	        		}
	        		return retUrl;
	        	}},
	    		{field:'edit',title:'编辑',width:35,align:'center',sortable:false,
					formatter:function(value,rowData,rowIndex){
						//if(Number(rowData.publish||'0')==1) return "N/A";
						var ret = "<a href='javascript:void(0)'><img width='12px' height='12px' style='border:0px' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='编辑' ";
						ret += " onClick='editTopic("+rowData.id+")'/></a>";
						return ret;
					}
				},
		        {field:'id',title:'消息ID',width:40,align:'center',sortable:false},
		        {field:'type',title:'消息分类',width:65,align:'center',sortable:false,
			    	  formatter:function(value, rowData, rowIndex){
			    		  var tn = '<span style="color:red">未知</span>';
			    		  switch(Number(value||'0')){
			    		  	case 1: tn ='<span style="color:grey">App普通消息</span>';break;
			    		  	case 2: tn ='<span style="color:grey">App横幅信息</span>';break;
			    		  	case 3: tn ='<span style="color:red">App轮播图</span>';break;
			    		  	case 5: tn ='<span style="color:black">App开机广告</span>';break;
			    		  	case 7: tn ='<span style="color:magenta">弹窗广告</span>';break;
			    		  	case 13: tn ='<span style="color:orange">Web轮播图</span>';break;
			    		  	case 101: tn ='<span style="color:blue">App活动广播</span>';break;
			    		  	case 102: tn ='<span style="color:green">App系统通知</span>';break;
			    		  }
			    		  return tn;
			    	  }
		        },
		   		{field:'messagedit',title:'发送通知',width:50,align:'center',sortable:false,
					formatter:function(value,rowData,rowIndex){
						if(Number(rowData.type||'0')!=102) return "N/A";
						var ret = "<a href='javascript:void(0)'><img width='12px' height='12px' style='border:0px' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/redo.png' title='指定用户' ";
						ret += " onClick='editMessage("+rowData.id+")'/></a>";
						return ret;
					}
				},
			    {field:'number',title:'序号',width:40,align:'center',sortable:false,
				   	  formatter:function(value, rowData, rowIndex){
			    		  if(!rowData.id) return "";
			    		  return "<a href='javascript:void(0)' onClick='editNotifyOrder("+rowData.id+","+rowData.number+")'>"+rowData.number+"</a>";
			    	  }
			    },
			    {field:'title',title:'标题',width:60,align:'center',sortable:false,},
			    
			    {field:'message',title:'消息内容',width:90,align:'left',sortable:false,
			    	  formatter:function(value, rowData, rowIndex){
			    		  if(!rowData.message){
			    			  return 'N/A';
			    		  }
			    		  if(rowData.message&&rowData.message.length>0){
			    			  	if(rowData.message.length>10){
			    			  		return rowData.message.substr(0,15)+'...';			    		
			    			  	}else{
			    			  		return rowData.message;
			    			  	}
			    		  }
			    	  }
			    },
				{field:'url',title:'链接',width:40,align:'center',sortable:false,
					  formatter:function(value, rowData, rowIndex){
					  	if(value){
					  		if(value.indexOf("http")>=0){//看是否加了带http的头消息
					  			return '<a href="'+rowData.url+'" target="_blank"><span style="color:red;">查看</span></a>';
				  			}
						  	return '<a href="http://'+rowData.url+'" target="_blank"><span style="color:red;">查看</span></a>';
						}else{
							return 'N/A';
						}
			        }
				},
				{field:'encrypt',title:'加密',width:30,align:'center',sortable:false,
			    	formatter:function(value, rowData, rowIndex){
		  		     	if(Number(value||'0')==1){
		  		     		return '<span style="color:red">是</span>';
			  		  	}
		  		     	return '否';
		        	}
			    },
			    {field:'valid',title:'状态',width:40,align:'center',sortable:false,
			    	formatter:function(value, rowData, rowIndex){
			    		var ret = '<span style="color:">未知</span>';
			    		if (value){
			    			switch(value){
			    			case 10: ret = '<span style="color:green;">未 开始</span>';break;
			    			case 20: ret = '<span>进 行中</span>';break;
			    			case 30: ret = '<span style="color:red;">已 结束</span>';break;
			    			}
			    		}
			    		return ret;
			    	}
			    },
			    {field:'start_time',title:'有效期开始时',width:75,align:'center',sortable:false,
			    	formatter:function(value, rowData, rowIndex){
		  		     	if(value){
		  		     		var show = value.substr(0,19);
		  		     		if(rowData.valid==10) {// 未开始
		  		     			show = '<span style="color:green">'+show+'</span>'
		  		     		}
		  		     		return show;
			  		  	}
		        	}
			    },
			    {field:'end_time',title:'有效期截止时',width:75,align:'center',sortable:false,
			    	formatter:function(value, rowData, rowIndex){
		  		     	if(value){
		  		     		var show = value.substr(0,19);
		  		     		if(rowData.valid==30) {// 过期
		  		     			show = '<span style="color:red">'+show+'</span>'
		  		     		}
		  		     		return show;
			  		  	}
			    	}
			    },
			    
			    {field:'create_time',title:'创建时间',width:55,align:'center',sortable:false,
			    	formatter:function(value, rowData, rowIndex){
		  		     	return '<span style="white-space:pre-wrap;">'+value+'</span>';
		        	}
		    	},
			    {field:'update_time',title:'修改时间',width:55,align:'center',sortable:false,
			       formatter:function(value, rowData, rowIndex){
		  		     	if(value){
		  		     		return '<span style="white-space:pre-wrap;">'+value+'</span>';
			  		  	}
		        	}
	        	}

	    ]],
	    hideColumn:['user_type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[{
			text:'添加消息',
			iconCls:'icon-add',
			handler:function(){
				addNotify();
			}
		},
		{
			text:'删除消息',
			iconCls:'icon-cancel',
			handler:function(){
				delNotify();
			}
		}]	
	});

}

/**
 * 初始化加载系统通知用户
 * @returns
 */
function refreshDicRight() {
	$('#rightGrid').datagrid({
		url:appPath + "/itbNotify/getNotifyUserMsgPg.action",
	    height:'360',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam3(),
	    singleSelect:false,
	    selectOnCheck:false,
	    // If true, the checkbox is checked/unchecked when the user clicks on a row. 
	    // If false, the checkbox is only checked/unchecked when the user clicks exactly on the checkbox.
	    checkOnSelect:true,
	    columns:[[
	        {field:'user_id',title:'用户ID',width:50,align:'left',sortable:false},
	        {field:'mobile',title:'手机号',width:50,align:'left',sortable:false,
	        	 formatter:function(value, rowData, rowIndex){
	        		 if(value){
	        			 	return rowData.mobile;
	        		 }
	        		 return 'N/A';
	        	 }
	        },
	        {field:'user_name',title:'用户名',width:50,align:'left',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        			var ret = '<span style="color:#EEE0E5;">暂无</span>';
	        			if (value){
	        				return '<span>'+value+'</span>';
	        			}
	        		return ret;
	        	}
	        },
			{field:'states',title:'<span style="color:red;">状态<发送通知></span>',width:50,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
        			return	"<a href='javascript:void(0)' class='easyui-linkbutton' iconCls='icon-search' " +
        					"onClick='editNotifyMsg("+rowData.user_id+","+rowData.notify_id+")'>Send</a>";
	        	}
			},
	        {field:'cnt',title:'已发送次数',width:50,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		var ret = '<span style="color:#1C86EE;">0</span>';
	        		if (value){
	        			ret = '<strong>'+value+'</strong>';
	        		}
	        		return ret;
	        	}
	        }
	    ]],
	    hideColumn:['user_type'],
	    pagination:true,
		rownumbers:true,
		toolbar: []  
	 });	
}

function refreshDicLeft() {
	$('#leftGrid').datagrid({
	    url:appPath + "/itbNotify/getNotifyEditMsgPg.action",
	    height:'360',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam2(),
	    singleSelect:false,
	    // If set to true, clicking a checkbox will always select the row. 
	    // If false, selecting a row will not check the checkbox.
	    selectOnCheck:true,
	    // If true, the checkbox is checked/unchecked when the user clicks on a row. 
	    // If false, the checkbox is only checked/unchecked when the user clicks exactly on the checkbox.
	    checkOnSelect:true,
	    columns:[[
			{field:'user_id',title:'用户ID',width:50,align:'left',sortable:false},
			{field:'mobile',title:'手机号',width:50,align:'left',sortable:false,
				 formatter:function(value, rowData, rowIndex){
					 if(value){
						 return rowData.mobile;
					 }
					 return 'N/A';
				 }
			},
			{field:'user_name',title:'用户名',width:50,align:'center',sortable:false,
				 formatter:function(value, rowData, rowIndex){
					 if(value){
						 return rowData.user_name;
					 }
					 return 'N/A';
				 }
			}
	    ]],
	    hideColumn:['user_type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[]
	});	
}
//添加用户消息关联
function editNotifyMsg(userId){
	$.messager.confirm('确认','<span style="color:red;">确认发送系统消息通知？</span>',function(r){
		if (r){// 确认导出
			var notifyId=$("#notifyId").val();
			if(userId){
				var url = appPath+"/itbNotify/addNotifyMsg.action"
				var sendData = {
						"notifyInfo.user_id": userId,
						"notifyInfo.notify_id": notifyId
				};
				$.loading(true);
				$.post(url, sendData, function(data){  
					if (data == "ok"){
						$("#meg").show('slow');
						window.setTimeout(function(){
							$("#meg").hide();
						},1000)
						$.loading(false);
						doQuery3();
					} else if(data == "no") {
						$.loading(false);
						$.messager.alert('提示信息','发送失败','info');
					}
				});
			}else{
				$.messager.alert('提示信息','发送失败','error');
			}
		}
	});
	
}
	
//只有是系统消息才会显示能编辑
function editMessage(Id){
	
	$("#notifyId").val(Id);	
	doQuery3();
	$("#msgBtn").show();
	$('#editMessage').window({
		title:'系统消息通知',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#editMessage').window('move',{top:20,left:20});
	$('#editMessage').window('open');
}


function closeMsgList(){
	$('#editMessage').window('close');
}

function editTopic(stId){	
	$("#editTable").show();
	$('#editForm').form('clear');
	$("#topicImg").html('').val('');
	
	$("#trForNew").hide();
	$("#trForEdit").show();
	//$("#editCurType").val(0);
	$("#showTypeForEdit").html('');
	
	$("#editStId").val(stId);
	var url = appPath + "/itbNotify/getNotifyInfoLst.action?id="+ stId;//映射专题编辑的信息
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			var type = Number(info.type||0);
			//var pType = Number(info.parent_type||0);
			//var type = Number(info.type||0);
			
			$("#editTopicTitle").val(info.title||'');
			$("#editTopicDesc").val(info.message||'');
			$("#editTopicUrl").val(info.url||'');
			$("#editNotifyUse").combobox('select',info.type||'');//大的分类
			
			$("#editNotifyUse").combobox({
				onBeforeLoad : function(){
					$("#editNotifyUse").combobox('select',info.type||'');//大的分类
				},
				onSelect : function(ret){
					if (ret.value == 7) {
						$("#editNotifyDisplay").combobox('select',info.display_type);//可使用的 
						$('#editEmbedUrl').attr('disabled',false);
						$("#editNotifyDisplay").combobox({disabled: false}); 
						$('#editEmbedW').attr('disabled',false);
						$('#editEmbedH').attr('disabled',false);
					} else {
						$("#editNotifyDisplay").combobox('select',0);//可使用的 
						$('#editEmbedUrl').attr('disabled',true);
						$("#editNotifyDisplay").combobox({disabled: true}); 
						$('#editEmbedW').attr('disabled',true);
						$('#editEmbedH').attr('disabled',true);
						$("#editEmbedUrl").val('');
						$("#editEmbedH").val('');
						$("#editEmbedW").val('');
					}
				}
			});
			
			$("#editEncrypt").combobox('select',info.encrypt||'0');
			$("#queryDateStartEdit").datebox('setValue',info.start_time||'');
			$("#queryDateEndEdit").datebox('setValue',info.end_time||'');
			$("#editCurType").val(type);
			$("#editTopicChkFreq").val(info.chk_freq||0);
			
			
			$("#editEmbedUrl").val(info.embed_url||'');
			$("#editEmbedW").val(info.embedW||'');
			$("#editEmbedH").val(info.embedH||'');
			
			if(type>0) {
				var show = '';
				switch(Number(type)){
					case 1: show = 'App普通消息';break;
					case 2: show = 'App横幅';break;
					case 3: show = 'App轮播图';break;
					case 5: show = 'App开机广告';break;
					case 7: show = '弹窗广告';break;
					case 13: show = 'Web轮播图';break;
					case 101: show = 'App活动广播';break;
					case 102: show = 'App系统通知';break;
				}
	
				$("#showTypeForEdit").html(show);
			}
			
			var showImg = '';
			if(info.image && info.image.length>0) {
				showImg = info.image.replace('oss-cn-hangzhou.aliyuncs.com','img-cn-hangzhou.aliyuncs.com')
					+'@200h_200w_1l.png';
			}
			var imgHtml = '<img src="'+showImg+'" style="display:inline;max-height:100px;max-width:200px">';
			$("#topicImg").append(imgHtml).val(info.image||'');
		}
	});
	
	$("#editBtn").show();
	$('#editDlg').window({
		title:'编辑消息',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	cancelPostData();// 上传图片清除 uploader = null
	initOSS();
	$('#editDlg').window('move',{top:20,left:20});
	$('#editDlg').window('open');
}
//添加消息内容
function addNotify(){
	$("#editTable").show();
	$('#editForm').form('clear');
	$("#topicImg").html('').val('');
	
	$("#trForNew").show();
	$("#trForEdit").hide();
	//$("#editCurType").val(0);
	//$("#editTopicType").combobox('select',1);

//	$("#editNotifyUse").combobox('select',3).combobox('enable');//可使用的 
	$("#editNotifyUse").combobox({
		onBeforeLoad : function(){
			$("#editNotifyUse").combobox('select',3).combobox('enable');//可使用的 
		},
		onSelect : function(ret){
			if (ret.value == 7){
				$("#editNotifyDisplay").combobox('select',1);//可使用的 
				$('#editEmbedUrl').attr('disabled',false);
				$("#editNotifyDisplay").combobox({disabled: false}); 
				$('#editEmbedW').attr('disabled',false);
				$('#editEmbedH').attr('disabled',false);
			} else {
				$("#editNotifyDisplay").combobox('select',0);//可使用的 
				$('#editEmbedUrl').attr('disabled',true);
				$("#editNotifyDisplay").combobox({disabled: true}); 
				$('#editEmbedW').attr('disabled',true);
				$('#editEmbedH').attr('disabled',true);
				$("#editEmbedUrl").val('');
				$("#editEmbedH").val('');
				$("#editEmbedW").val('');
			}
		}
	});
	
	$("#editEncrypt").combobox('select',0);
	
	
	$("#editBtn").show();
	$('#editDlg').window({
		title:'新建消息',
		iconCls:'icon-add',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	cancelPostData();// 上传图片清除 uploader = null
	initOSS();
	
	$('#editDlg').window('move',{top:20,left:150});
	$('#editDlg').window('open');
}

// 确定编辑
function doEdit(){
	var stId = $("#editStId").val();//消息ID
	var type = $("#editNotifyUse").combobox('getValue');
	var disPlayVal = $("#editNotifyDisplay").combobox('getValue');

	var embedUrl = $("#editEmbedUrl").val();
	var embedUrlW = $("#editEmbedW").val();
	var embedUrlH = $("#editEmbedH").val();
	
	var encrypt = $("#editEncrypt").combobox('getValue');
	var title = $("#editTopicTitle").val();
	var message = $("#editTopicDesc").val();
	var imgUrl = $("#topicImg").val();
	var Url = $("#editTopicUrl").val();
	var start_time = $("#queryDateStartEdit").datebox('getValue');
	var end_time = $("#queryDateEndEdit").datebox('getValue');
	var chkFreq = $("#editTopicChkFreq").val();
	
	if(Number(type||0)<=0){
		return $.messager.alert('提示信息','请选择消息分类','info');
	}
	
	if (!title){
		return $.messager.alert('注意','标题不能为空!','warning');
	}
	
	if (!chkInputDate(start_time) || !chkInputDate(end_time)){
		return $.messager.alert('注意','请填写有效时间!','warning');
	}
	
	
	if (type && type == 7){
		if (!embedUrl){
			$.messager.alert('警告信息','弹窗广告必须输入嵌入网页!','warning')
			return;
		}
	}
	
	var url = appPath+"/itbNotify/addNotify.action";
	var sendData = {
		"notifyInfo.id": stId||"",
		"notifyInfo.type": Number(type),
		"notifyInfo.display_type": Number(disPlayVal),
		"notifyInfo.title": title || "",
		"notifyInfo.message": message || "",
		"notifyInfo.image":imgUrl||"",
		"notifyInfo.url":Url||"",
		"notifyInfo.embed_url":embedUrl||"",
		"notifyInfo.embedW":embedUrlW||"",
		"notifyInfo.embedH":embedUrlH||"",
		"notifyInfo.encrypt":encrypt||0,
		"notifyInfo.start_time":start_time||"",
		"notifyInfo.end_time":end_time||"",
		"notifyInfo.chk_freq":Number(chkFreq||'0')||0
	};
	
    $.post(url, sendData, function(data){  
		if (data == "ok") { 
			$.messager.alert('提示信息','提交成功','info');
			$('#editDlg').window('close');
			doQuery();
        } else {
        	$.messager.alert('提示信息','提交失败','info');
        }
    });
}


// 判断时间有效性
function chkInputDate(str){
	var reg = /^(\d+)-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;  
	var r = str.match(reg); 
	if(r==null)return '';  
	r[2]=r[2]-1;  
	var d= new Date(r[1], r[2],r[3], r[4],r[5], r[6]);  
	if(d.getFullYear()!=r[1])return '';  
	if(d.getMonth()!=r[2])return '';  
	if(d.getDate()!=r[3])return '';  
	if(d.getHours()!=r[4])return '';  
	if(d.getMinutes()!=r[5])return '';  
	if(d.getSeconds()!=r[6])return '';  
	return str;  
}

//删除消息内容
function delNotify(){
	var selectItem=$("#tmplGrid").datagrid("getChecked");//获取勾选框
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择项目！','warning');
		return;
	}
	
	$.messager.confirm("确认", "是否确认[删除]所选项目?</span>",
		function(r){
	        if (r) { 
				var ids = "";
				$.each(selectItem, function(index, item){
					ids = ids + item.id + ",";
				});
				var url = appPath+"/itbNotify/delNotify.action?ids="+ids;
				$.post(url,function(data){
					if(data=="ok"){
						$.messager.alert('提示信息','删除成功','info');
						doQuery();
					}else{
						$.messager.alert('提示信息','删除失败','info');
					}
				});
	        }
		}
	);
}


/**
 * 显示顺序
 */
function editNotifyOrder(id,number){
	$("#notifyId").val(id);
	$("#notify").val(number);
	
	$("#notifyBtn").show();
	$('#notifyDlg').window({
		title:'显示顺序设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#notifyDlg').window('move',{top:20,left:20});
	$('#notifyDlg').window('open');
}
/**
 * 修改显示顺序
 */
function doUpdNotify(){
	var id = $("#notifyId").val();
	var number = $("#notify").val();
	if(!number || number.length == 0 || Number(number)>999 || Number(number)<=0){
		$.messager.alert('提示信息','有效数值范围为：1～999','warning');
		return;
	}
	
	var url = appPath+"/itbNotify/updNotifyOrder.action?orderid="+id+"&number="+number;
	$.post(url,function(data){
		if(data=="ok"){
			$.messager.alert('提示信息','显示顺序已更新！','info',function(){
				doQuery();
				$('#notifyDlg').window('close');
			});
		}else {
			$.messager.alert('提示信息','显示顺序更新失败！','warning');
		}
	});
}
/**
 * 结束显示顺序编辑
 */
function cancelUpdNotify(){
	$('#notifyDlg').window('close');
}

function cancelEdit(){
	$('#editDlg').window('close');
}

//查询参数条件
function getQueryParam(){
    
	var queryObject = {};
	var findDtS = $("#queryDateStart").datebox('getValue');// 获取开始结束日期
	var findDtE = $("#queryDateEnd").datebox('getValue');
	var findType= $("#editNotifyType").combobox('getValue');// 获取类型			
	//var isCount = $("#queryCount").val().trim();// 是否统计
	var findTitleName=$("#queryTitleName").val().trim();// 标题名字
	var findValid = $("#queryNotifyState").combobox('getValue');// 消息状态

	if(findType && Number(findType||'0')>0) queryObject.findNotifyType = findType;// 类型

	if(findTitleName&&findTitleName.length>0) queryObject.findTitleName = findTitleName;// 样版名称
	if(findDtS && findDtS.length>0) queryObject.findDateStart = findDtS+' 00:00:00 ';
	if(findDtE && findDtE.length>0) queryObject.findDateEnd = findDtE+' 23:59:59 ';
	if (findValid && Number(findValid)>0) queryObject.findValid = findValid;
	return queryObject;
}

function getQueryParam2(){
	var queryObject = {};
	var notify_id=$("#notifyId").val();
	if(notify_id && Number(notify_id||'0')>0) queryObject.notify_id = notify_id;// 类型

	return queryObject;
}

// 右边列表手机号查询
function getQueryParam3(){
	var queryObject = {};

	var findMobile=$('#queryNotifyMobile').val().trim();// 手机号查询
	var notify_id=$("#notifyId").val();

	if (findMobile && Number(findMobile)){// 手机号验证 (/^1[3|4|5|8][0-9]\d{4,8}$/.test(findMobile)
		queryObject.findMobile = findMobile;// 手机
	} 
	if (notify_id && Number(notify_id||'0')>0){
		queryObject.notify_id = notify_id;// 类型
	} 

	return queryObject;
}

/**
 * 查询数据
 */
function doQuery(){
	$("#tmplGrid").datagrid('unselectAll');
	$("#tmplGrid").datagrid('load',getQueryParam());
}

function doQuery2(){
	$("#leftlGrid").datagrid('unselectAll');
	$("#leftlGrid").datagrid('load',getQueryParam2());
	refreshDicLeft();
}

function doQuery3(){
	$("#rightlGrid").datagrid('unselectAll');
	$("#rightlGrid").datagrid('load',getQueryParam3());
	refreshDicRight();
}


// ******************************** 上传图片 *******************************
var myDomain = 'http://7xogoq.com1.z0.glb.clouddn.com';
var ossDmain = "http://itbour-back.oss-cn-hangzhou.aliyuncs.com/";
var validFile = false;
var uploader = null;

// 图像缩放
function DrawImage(ImgD,FitWidth,FitHeight){
    var image=new Image();
    image.src=ImgD.src;
    if(image.width>0 && image.height>0){
        if(image.width/image.height>= FitWidth/FitHeight){
            if(image.width>FitWidth){
                ImgD.width=FitWidth;
                ImgD.height=(image.height*FitWidth)/image.width;
            }else{
                ImgD.width=image.width; 
               ImgD.height=image.height;
            }
        } else{
            if(image.height>FitHeight){
                ImgD.height=FitHeight;
                ImgD.width=(image.width*FitHeight)/image.height;
            }else{
                ImgD.width=image.width; 
               ImgD.height=image.height;
            } 
       }
    }
}

function isImage(url) {
    var res, suffix = "";
    var imageSuffixes = ["png", "jpg", "jpeg", "gif", "bmp"];
    var suffixMatch = /\.([a-zA-Z0-9]+)(\?|\@|$)/;

    if (!url || !suffixMatch.test(url)) {
        return false;
    }
    res = suffixMatch.exec(url);
    suffix = res[1].toLowerCase();
    for (var i = 0, l = imageSuffixes.length; i < l; i++) {
        if (suffix === imageSuffixes[i]) {
            return true;
        }
    }
    return false;
}

function doPostData(){// 开始上传
	if (validFile && uploader) {
		uploader.start();
	} else {
		setMsg("red", "请选择图像文件！");
	}
}

function cancelPostData(){ // 取消上传
	if (uploader) {
		uploader.destroy();
		uploader = null;
	}
}

function setMsg(color, msg) {
	$.messager.alert('提示信息',msg,'info');
}

function fmtCreateTime(value, rowData, rowIndex){
	if(!value)return "";
	var s = new Date(value);
	return rowData.create_time=$.DateUtil.format(s,'yyyy/MM/dd hh:mm:ss');
}

function fmtHotFlag(value, rowData, rowIndex){
	if(rowData.hotFlag==1)return "是";
	return "否";
}





// ############### FOR OSS UPLOAD START ###############
//var accessid= '';
//var accesskey= '';
//var uploadHost = 'http://itbour-back.oss-cn-hangzhou.aliyuncs.com';
var g_object_name = '';
var dtNow = Date.parse(new Date()); //Date.parse(new Date())/1000;
//var policyText = {
//"expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
//"conditions": [
//  ["content-length-range", 0, 104857600] // 设置上传文件的大小限制
//]
//};
//var policyJsonStr = JSON.stringify(policyText);
//var policyBase64 = Base64.encode(policyJsonStr);
//var message = policyBase64;
//var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true });
//var signature = Crypto.util.bytesToBase64(bytes);

var OSS_PARAM = {
	expire: 0,
	uploadHost: '',
	accessKeyId: '',
	policyBase64: '',
	signature: '',
	flg: false
};

function randomString(len) {
	len = len || 20;
	var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';   
	var maxLen = chars.length;
	var str = '';
	for (var i = 0; i < len; i++) {
		str += chars.charAt(Math.floor(Math.random() * maxLen));
    }
	return str;
}

function getSuffix(filename) {
    var pos = filename.lastIndexOf('.');
    var suffix = '';
    if (pos != -1) {
        suffix = filename.substring(pos);
    }
    return suffix;
}

function calculate_object_name(filename) {
	if (g_object_name){
		g_object_name = '';
	}
	var now = new Date(); 
	var nowStr = now.format("yyyy/MM/dd/hhmmssS_");
    g_object_name = "image/U"+g_userId+"/"+nowStr + randomString(20);
}

function set_upload_param(up, filename, ret) {
	// 判断当前expire是否超过了当前时间,如果超过了则重新取
	dtNow = Date.parse(new Date());//  Date.parse(new Date())/1000
	OSS_PARAM.flg = false;
    if (OSS_PARAM.expire < dtNow + 5000) {// 5s
    	var url = appPath+"/itbImg/getOSSToken.action";
        $.get(url, function(data){  
    		if (data && data.signature) { 
    			OSS_PARAM.expire = data.expire;
    			OSS_PARAM.uploadHost = data.uploadHost;
    			OSS_PARAM.accessKeyId = data.accessKeyId;
    			OSS_PARAM.policyBase64 = data.policyBase64;
    			OSS_PARAM.signature = data.signature;
    			OSS_PARAM.flg = true;
    			
    			doUpStart(up, filename, ret);
            } else {
            	$.messager.alert('提示信息','上传异常, 请重新尝试!','info');
            }  
        });
    } else {
    	doUpStart(up, filename, ret);
    }
}

function doUpStart(up, filename, ret){
	if (filename && filename != '') {
        calculate_object_name(filename);
    }
    var new_multipart_params = {
        'key' : g_object_name,
        'policy': OSS_PARAM.policyBase64,
        'OSSAccessKeyId': OSS_PARAM.accessKeyId, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'signature': OSS_PARAM.signature,
    };

    up.setOption({
        'url': OSS_PARAM.uploadHost,
        'multipart_params': new_multipart_params
    });

    up.start();
}

function clearUploadList() {
	$("#topicImg").html('');
	$("#topicImg").val('');
}

function initOSS() {
	if (uploader) {
		uploader.destroy();
		uploader = null;
	}

	uploader = new plupload.Uploader({
		runtimes : 'html5,flash,silverlight,html4',
		browse_button : 'selFiles', 
	    //multi_selection: false,
		//container: document.getElementById('container'),
		//flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
		//silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
	    url : 'http://oss.aliyuncs.com',
		init: {
			PostInit: function() {// 当Init事件发生后触发
//				document.getElementById('upImgFile').onclick = function() {
//		            set_upload_param(uploader, '', false);
//		            return false;
//				};
			},

			FilesAdded: function(up, files) {
				clearUploadList();
				$('#uploadMsg').hide();
				
				var delLen = (up.files.length>=files.length)?(up.files.length-files.length):up.files.length;
				up.splice(0,delLen);
				
				var bAllOk = true;
				plupload.each(files, function(file) {
					if (isImage(file.name)) {
						// add file info list
						set_upload_param(uploader, '', false);
				        return false;
					} else {
						bAllOk = false;
						var ngFile = up.getFile(file.id);
						if (ngFile) {
							up.removeFile(ngFile);
						}
					}
				});
				
				if (!bAllOk) {
					setMsg("red", "已过滤非图像文件！");
				}     
			},

			BeforeUpload: function(up, file) {
	            set_upload_param(up, file.name, true);
	        },

			UploadProgress: function(up, file) {
//				var d = document.getElementById(file.id);
//				d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
//	            var prog = d.getElementsByTagName('div')[0];
//				var progBar = prog.getElementsByTagName('div')[0];
//				progBar.style.width= 2*file.percent+'px';
//				progBar.setAttribute('aria-valuenow', file.percent);
//				setMsg("green", file.name + ' 上传中...');
			},

			FileUploaded: function(up, file, info) {
	            if (info.status == 200) {
	            	console.log(g_object_name);
	            	var showImg = '';
	            	var tmp = ossDmain+g_object_name
	    			if(g_object_name && g_object_name.length>0) {
	    				showImg = tmp+'?x-oss-process=image/resize,m_pad,h_150,w_150,color_cccccc';
	    			}
	    			var imgHtml = '<img src="'+showImg+'" style="display:inline;max-height:100px;max-width:200px">';
	    			$("#topicImg").append(imgHtml).val(tmp||'');
	        		setMsg("green", '上传成功!');
	            }
	            else {
	            	setMsg("red", '上传出错！');
	            	document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
	            }
			},

			Error: function(up, err) {
//				document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
				setMsg("red", err.response);
			}
		}
	});
	
	uploader.init();
}
//############### FOR OSS UPLOAD END ###############